/**
 * 地理位置服务模块
 */
class LocationService {
  constructor() {
    this.defaultLocation = {
      latitude: 39.90923, // 北京天安门
      longitude: 116.397428,
      address: '北京市东城区'
    }
  }

  /**
   * 获取用户当前位置
   */
  getCurrentLocation() {
    return new Promise((resolve, reject) => {
      wx.getLocation({
        type: 'gcj02',
        altitude: false,
        success: (res) => {
          console.log('获取位置成功:', res)
          
          const location = {
            latitude: res.latitude,
            longitude: res.longitude,
            accuracy: res.accuracy,
            speed: res.speed,
            altitude: res.altitude
          }
          
          // 保存到全局数据
          const app = getApp()
          app.globalData.location = location
          
          resolve(location)
        },
        fail: (error) => {
          console.error('获取位置失败:', error)
          
          let message = '获取位置失败'
          if (error.errMsg.includes('auth deny')) {
            message = '位置权限被拒绝'
          } else if (error.errMsg.includes('timeout')) {
            message = '定位超时'
          }
          
          reject(new Error(message))
        }
      })
    })
  }

  /**
   * 检查位置权限
   */
  checkLocationPermission() {
    return new Promise((resolve, reject) => {
      wx.getSetting({
        success: (res) => {
          if (res.authSetting['scope.userLocation'] === false) {
            // 用户拒绝了位置权限
            wx.showModal({
              title: '需要位置权限',
              content: '为了为您推荐附近的店铺，需要获取您的位置信息',
              confirmText: '去设置',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  wx.openSetting({
                    success: (settingRes) => {
                      if (settingRes.authSetting['scope.userLocation']) {
                        resolve(true)
                      } else {
                        reject(new Error('未开启位置权限'))
                      }
                    }
                  })
                } else {
                  reject(new Error('需要位置权限'))
                }
              }
            })
          } else {
            // 有权限或未询问过
            resolve(true)
          }
        },
        fail: () => {
          reject(new Error('获取权限信息失败'))
        }
      })
    })
  }

  /**
   * 安全获取位置（包含权限检查）
   */
  async safeGetLocation() {
    try {
      await this.checkLocationPermission()
      const location = await this.getCurrentLocation()
      return location
    } catch (error) {
      console.warn('获取位置失败，使用默认位置:', error.message)
      
      // 使用默认位置
      const app = getApp()
      app.globalData.location = this.defaultLocation
      
      return this.defaultLocation
    }
  }

  /**
   * 计算两点间距离（Haversine公式）
   */
  calculateDistance(lat1, lon1, lat2, lon2) {
    const R = 6371 // 地球半径（公里）
    const dLat = this.toRadians(lat2 - lat1)
    const dLon = this.toRadians(lon2 - lon1)
    
    const a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
              Math.cos(this.toRadians(lat1)) * Math.cos(this.toRadians(lat2)) *
              Math.sin(dLon / 2) * Math.sin(dLon / 2)
    
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a))
    const distance = R * c
    
    return Math.round(distance * 100) / 100 // 保留两位小数
  }

  /**
   * 角度转弧度
   */
  toRadians(degrees) {
    return degrees * (Math.PI / 180)
  }

  /**
   * 格式化距离显示
   */
  formatDistance(distance) {
    if (distance < 1) {
      return `${Math.round(distance * 1000)}m`
    } else {
      return `${distance.toFixed(1)}km`
    }
  }

  /**
   * 计算配送时间
   */
  calculateDeliveryTime(distance, baseTime = 20) {
    // 基础配送时间 + 距离因子
    const timePerKm = 5 // 每公里增加5分钟
    const deliveryTime = baseTime + Math.round(distance * timePerKm)
    
    // 最小15分钟，最大60分钟
    return Math.max(15, Math.min(60, deliveryTime))
  }

  /**
   * 格式化配送时间显示
   */
  formatDeliveryTime(minutes) {
    if (minutes < 60) {
      return `${minutes}分钟`
    } else {
      const hours = Math.floor(minutes / 60)
      const mins = minutes % 60
      return mins > 0 ? `${hours}小时${mins}分钟` : `${hours}小时`
    }
  }

  /**
   * 逆地理编码（坐标转地址）
   */
  async reverseGeocode(latitude, longitude) {
    return new Promise((resolve, reject) => {
      // 使用微信小程序的逆地理编码API
      wx.request({
        url: 'https://apis.map.qq.com/ws/geocoder/v1/',
        data: {
          location: `${latitude},${longitude}`,
          key: 'YOUR_TENCENT_MAP_KEY', // 需要申请腾讯地图API密钥
          get_poi: 1
        },
        success: (res) => {
          if (res.data.status === 0) {
            const result = res.data.result
            const address = {
              formatted_address: result.formatted_addresses.recommend,
              province: result.address_component.province,
              city: result.address_component.city,
              district: result.address_component.district,
              street: result.address_component.street,
              street_number: result.address_component.street_number
            }
            resolve(address)
          } else {
            reject(new Error('地址解析失败'))
          }
        },
        fail: () => {
          reject(new Error('网络请求失败'))
        }
      })
    })
  }

  /**
   * 地理编码（地址转坐标）
   */
  async geocode(address) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://apis.map.qq.com/ws/geocoder/v1/',
        data: {
          address: address,
          key: 'YOUR_TENCENT_MAP_KEY'
        },
        success: (res) => {
          if (res.data.status === 0) {
            const location = res.data.result.location
            resolve({
              latitude: location.lat,
              longitude: location.lng
            })
          } else {
            reject(new Error('地址解析失败'))
          }
        },
        fail: () => {
          reject(new Error('网络请求失败'))
        }
      })
    })
  }

  /**
   * 选择位置
   */
  chooseLocation() {
    return new Promise((resolve, reject) => {
      wx.chooseLocation({
        success: (res) => {
          const location = {
            name: res.name,
            address: res.address,
            latitude: res.latitude,
            longitude: res.longitude
          }
          resolve(location)
        },
        fail: (error) => {
          if (error.errMsg.includes('cancel')) {
            reject(new Error('用户取消选择'))
          } else {
            reject(new Error('选择位置失败'))
          }
        }
      })
    })
  }

  /**
   * 打开地图查看位置
   */
  openLocation(latitude, longitude, name = '', address = '') {
    wx.openLocation({
      latitude: parseFloat(latitude),
      longitude: parseFloat(longitude),
      name,
      address,
      scale: 18
    })
  }

  /**
   * 获取附近店铺并计算距离
   */
  async getNearbyStoresWithDistance(stores, userLocation = null) {
    try {
      // 如果没有提供用户位置，尝试获取当前位置
      if (!userLocation) {
        userLocation = await this.safeGetLocation()
      }

      // 为每个店铺计算距离和配送时间
      const storesWithDistance = stores.map(store => {
        const distance = this.calculateDistance(
          userLocation.latitude,
          userLocation.longitude,
          store.latitude,
          store.longitude
        )

        const deliveryTime = this.calculateDeliveryTime(distance)

        return {
          ...store,
          distance,
          distanceText: this.formatDistance(distance),
          deliveryTime,
          deliveryTimeText: this.formatDeliveryTime(deliveryTime)
        }
      })

      // 按距离排序
      storesWithDistance.sort((a, b) => a.distance - b.distance)

      return storesWithDistance

    } catch (error) {
      console.error('计算店铺距离失败:', error)
      return stores
    }
  }

  /**
   * 检查是否在配送范围内
   */
  isInDeliveryRange(storeLocation, userLocation, maxDistance = 10) {
    const distance = this.calculateDistance(
      userLocation.latitude,
      userLocation.longitude,
      storeLocation.latitude,
      storeLocation.longitude
    )

    return distance <= maxDistance
  }

  /**
   * 获取当前城市
   */
  async getCurrentCity() {
    try {
      const location = await this.safeGetLocation()
      const address = await this.reverseGeocode(location.latitude, location.longitude)
      return address.city
    } catch (error) {
      console.error('获取当前城市失败:', error)
      return '北京市' // 默认城市
    }
  }

  /**
   * 保存常用地址
   */
  saveFrequentAddress(address) {
    try {
      let addresses = wx.getStorageSync('frequent_addresses') || []
      
      // 检查是否已存在
      const exists = addresses.find(addr => 
        addr.latitude === address.latitude && 
        addr.longitude === address.longitude
      )

      if (!exists) {
        addresses.unshift(address)
        // 最多保存10个常用地址
        if (addresses.length > 10) {
          addresses = addresses.slice(0, 10)
        }
        wx.setStorageSync('frequent_addresses', addresses)
      }
    } catch (error) {
      console.error('保存常用地址失败:', error)
    }
  }

  /**
   * 获取常用地址
   */
  getFrequentAddresses() {
    try {
      return wx.getStorageSync('frequent_addresses') || []
    } catch (error) {
      console.error('获取常用地址失败:', error)
      return []
    }
  }
}

// 创建实例
const locationService = new LocationService()

module.exports = locationService 